<?php
declare(strict_types=1);

namespace app\model;

use think\Model;
use think\facade\Cache;

class PlatformConfig extends Model
{
    protected $autoWriteTimestamp = true;

    // 获取配置缓存值
    public static function getConfigValue(string $key, $default = null)
    {
        $cacheKey = "platform_config_{$key}";
        $value = Cache::get($cacheKey);
        
        if ($value === null) {
            $config = self::where('config_key', $key)->find();
            $value = $config ? $config->config_value : $default;
            Cache::set($cacheKey, $value, 3600);
        }
        
        return $value;
    }

    // 设置配置值
    public static function setConfigValue(string $key, $value): bool
    {
        $config = self::where('config_key', $key)->findOrEmpty();
        $config->config_key = $key;
        $config->config_value = $value;
        $result = $config->save();
        
        if ($result) {
            Cache::delete("platform_config_{$key}");
        }
        
        return (bool)$result;
    }

    // 批量获取配置
    public static function getConfigValues(array $keys, array $defaults = []): array
    {
        $values = [];
        foreach ($keys as $key) {
            $values[$key] = self::getConfigValue($key, $defaults[$key] ?? null);
        }
        return $values;
    }
} 